package com.itheima.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//自定义拦截器
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    //目标资源方法执行前执行。 返回true：放行    返回false：不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        if (!StringUtils.hasLength(token)) {
            Result resultResponse = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(resultResponse);
            response.getWriter().write(json);
            return false;
        }
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            Result resultResponse = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(resultResponse);
            response.getWriter().write(json);
            return false;
        }

        return true; //true表示放行
    }
}